package com.atguigu.srb.core.controller.api;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.result.R;
import com.atguigu.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Api(tags = "用户绑定管理")
@RequestMapping("/api/core/userBind")
@Slf4j
public class WebUserBindController {

    @Autowired
    private UserBindService userBindService;

    // 调用汇付宝实现账户创建
    //用户绑定汇付宝平台url地址
    public static final String USERBIND_URL = "http://localhost:9999/userBind/BindAgreeUserV2";
    //用户绑定异步回调
    public static final String USERBIND_NOTIFY_URL = "http://localhost/api/core/userBind/notify";
    //用户绑定同步回调
    public static final String USERBIND_RETURN_URL = "http://localhost:3000/user";
    @ApiOperation(value = "用户绑定账户请求")
    @PostMapping("/auth/bind")
    public R bind(@RequestBody UserBindVO userBindVO, HttpServletRequest request) {
        // 从head中获取Token,并对token进行校验,确保用户已经登录,并从token中获取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        // 根据userId进行账户绑定
        String formStr = userBindService.commitBindUser(userBindVO, userId);

        return R.ok().data("formStr", formStr);
    }

    // 尚融宝回调接口
    @ApiOperation(value = "用户绑定账户异步回调接口")
    @PostMapping("/notify")
    public String asyncNotify(HttpServletRequest request) {
        // 获取汇付宝先srb发起回调的请求参数
        Map<String, String[]> requestParameterMap = request.getParameterMap();
        Map<String, Object> paramMap = RequestHelper.switchMap(requestParameterMap);
        log.info("账户绑定的回调接收参数如下:"+ JSON.toJSONString(paramMap));

        // 校验签名
        boolean resSign = RequestHelper.isSignEquals(paramMap);
        if (!resSign){
            log.info("用户账户绑定异步回调签名验证错误: " +JSON.toJSONString(paramMap));
            return "fail";
        }
        else {
            userBindService.asyncNotify(paramMap);
        }

        // 修改绑定状态

        return  "success";
    }


}
